package com.elm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.elm.mapper.PersonMapper;
import com.elm.mapper.UserAuthorityMapper;
import com.elm.mapper.UserMapper;
import com.elm.po.Authority;
import com.elm.po.Person;
import com.elm.po.User;
import com.elm.service.PersonService;
import com.elm.util.JwtUtil;

import jakarta.servlet.http.HttpServletRequest;

@Service
public class PersonServiceImpl implements PersonService{
    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAuthorityMapper userAuthorityMapper;
    @Autowired
    private HttpServletRequest request;
    
    private String getCurrentUsername() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUsernameFromToken(token);
    }

    private String getCurrentUserType() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUserTypeFromToken(token);
    }
    
    // 事务保证：同时插入user和person，要么都成功要么都失败
    @Transactional
    @Override
    public Person createPerson(Person person) {
    	String currentusername=getCurrentUsername();
    	String currentusertype=getCurrentUserType();
    	System.out.println(currentusername);
    	System.out.println(currentusertype);
    	if(!currentusertype.equals("ADMIN"))
    	 {
            throw new RuntimeException("权限不足：仅管理员可以新建");
        }
        // 1. 插入用户基本信息到user表（Person继承自User，可直接强转）
        User user = (User) person;
        userMapper.createUser(user);
        //2.插入权限
        List<Authority> authorities = person.getAuthorities();
        int admin=0,business=0,User=0;
        if (authorities != null && !authorities.isEmpty()) {
            for (Authority auth : authorities) {
                if(auth.getName().equals("ADMIN")) admin++;
                if(auth.getName().equals("BUSINESS")) business++;
                if(auth.getName().equals("USER")) User++;
            }
            if(admin!=0) userAuthorityMapper.addUserAuthority(user.getId(), "ADMIN");
            else if(business!=0) userAuthorityMapper.addUserAuthority(user.getId(), "BUSINESS");
            else if(User!=0) userAuthorityMapper.addUserAuthority(user.getId(), "USER");
        }
        person.setId(userMapper.getUserIdByName(user.getUsername()));
        // 3. 插入个人详情到person表
        personMapper.createPerson(person);
        return personMapper.getPersonById(person.getId());
    }
 
    // 新增：根据username查询person
    @Override
    public Person getPersonById(int id) {
    	User user= userMapper.getUserById(id);
    	if (!user.getUsername().equals(getCurrentUsername()) && !getCurrentUserType().equals("ADMIN")) {
			throw new RuntimeException("权限不足：仅用户本人及ADMIN可查看信息");
		}
        return personMapper.getPersonById(id);
    }

    
	@Override
	public Person updatePerson(Person person) {
		User user= userMapper.getUserById(person.getId());
		if (!user.getUsername().equals(getCurrentUsername()) && !getCurrentUserType().equals("ADMIN")) {
			throw new RuntimeException("权限不足：仅用户本人及ADMIN可更新信息");
		}
		personMapper.updatePerson(person);
		return personMapper.getPersonById(person.getId());
	}
	
	
}